import { useState, useEffect, useContext, useRef } from 'react'
import PanelLeft from '../../../../../common/PanelLeft';
import { Button, Collapse, Tooltip, Tree } from 'antd';
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import Api from '../../../../../../utils/api';
import FetchHelper from '../../../../../../utils/helper/fetch-helper';
import { dataToFeature, navByWkt, createLayer } from '../../../../../../utils/helper/mapHelper';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import Circle from 'ol/style/Circle';
import JzzyApi from '../../../../../../utils/apis/JzzyApi';
import ZhfxApi from '../../../../../../utils/apis/ZhfxApi';
import ZdfhApi from '../../../../../../utils/apis/ZdfhApi';
import { Icon } from 'ol/style';
import { resourcePath } from '../../../../../../utils/resource';
import { cacheDatas } from '../../../../../../utils/constant';
import useMap from '../hooks/useMap';
import MapPointerMove from '../common/MapPointerMove';
import DataDetail from '../common/DataDetail';
import BlockPanel from '../common/BlockPanel';
// import Toolbar from './Toolbar';

const generateData = (datas, dl) => {
    datas.forEach(data => {
        data.dl = dl;
        if (data.children) {
            generateData(data.children, dl)
        }
    });
    return datas
}
const fields = ['cztmc', 'jzzymc', 'yhmc'];
export default function RiskDanger(props) {
    const map = useMap();
    const [layers, setLayers] = useState([])
    const [visible, setVisible] = useState(true);

    const [layerDatas, setLayerDatas] = useState([]);

    useEffect(() => {
        Promise.all([Api.getZhfxCategroy(), Api.getCztCategroy(), Api.getJzzyCategroy(), Api.getZdfhCategroy(), FetchHelper.getJson(`/admin-api/ybyj/yhsj/count/by/yhlb`), FetchHelper.getJson(`/admin-api/ybyj/czt/countZl`), FetchHelper.getJson(`/admin-api/ybyj/jzzy/countZl`)]).then(([resp1, resp2, resp3, resp4, resp_1, resp_2, resp_3]) => {
            resp1.forEach((e, i) => {
                // 如果有 children，处理子元素
                if (e.children) {
                    e.children.forEach(r => {
                        r.count = r.title; // 设置子元素的 count
                    });
                }

                // 默认 count 为 title
                e.count = `${e.title} ( 0 ) `;

                const datas = resp_1.data.filter(d => {
                    return d.yhlb && e.title.includes(`${d.yhlb}`)
                })
                e.count = `${e.title} (${_.sumBy(datas, 'count')}) `; // 更新 count
                // 遍历 resp_1.data
                // resp_1.data.forEach((c,i) => {
                //     // 检查 title 是否包含 yhlb
                //     if (e.title.includes(`${c.yhlb}`)) {
                //         console.log("@:true1", e, c); // 输出匹配信息
                //         e.count = `${e.title} (${c.count}) `; // 更新 count
                //     }
                // });

                //console.log("@:", e, resp_1); // 输出当前元素及 resp_1
            });
            resp2.forEach((e, i) => {
                // 如果有 children，处理子元素
                if (e.children) {
                    e.children.forEach(r => {
                        r.count = r.title; // 设置子元素的 count
                    });
                }

                // 默认 count 为 title
                e.count = `${e.title} ( 0 ) `;

                // 遍历 resp_1.data
                resp_2.data.forEach((c, i) => {
                    // 检查 title 是否包含 yhlb
                    if (e.title.includes(`${c.cztzl === "" ? null : c.cztzl}`)) {
                        console.log("@:true2", e, c); // 输出匹配信息
                        e.count = `${e.title} (${c.count ? c.count : 0}) `; // 更新 count
                    }
                });

                console.log("@:", e, resp_2); // 输出当前元素及 resp_1
            });
            resp3.forEach((e, i) => {
                // 如果有 children，处理子元素
                if (e.children) {
                    e.children.forEach(r => {
                        r.count = r.title; // 设置子元素的 count
                    });
                }

                // 默认 count 为 title
                e.count = `${e.title} ( 0 ) `;

                // 遍历 resp_1.data
                resp_3.data.forEach((c, i) => {
                    // 检查 title 是否包含 yhlb
                    //console.log("@:true<-", e.title, c.jzzyzl);
                    if (e.title.includes(`${c.jzzyzl}`)) {
                        //console.log("@:true", e.title, c.jzzyzl); // 输出匹配信息
                        e.count = `${e.title} (${c.count ? c.count : 0}) `; // 更新 count
                    }
                });

                //console.log("@:", e, resp_3); // 输出当前元素及 resp_1
            });
            resp4.map((e, i) => {
                if (e.children) {
                    e.children.map(r => {
                        r.count = r.title
                        return r
                    })
                }
                //console.log("@:",e,resp_1)
                e.count = `${e.title} ( 0 ) `;
                return e
            });
            setLayerDatas([{
                title: "灾害风险",
                children: generateData(resp1, 'zhfx'),
                dl: 'zhfx'
            }, {
                title: "承灾体",
                children: generateData(resp2, 'czt'),
                dl: 'czt'
            }, {
                title: "减灾资源",
                children: generateData(resp3, 'jzzy'),
                dl: 'jzzy'
            },

            {
                title: "重点防护目标",
                children: generateData(resp4, 'zdfh'),
                dl: 'zdfh'
            }

            ])
        })
    }, [])


    useEffect(() => {
        if (!map) {
            return;
        }
        const layers = [];
        const generate = (datas) => {
            datas.forEach(data => {
                if (data.children) {
                    generate(data.children);
                } else {
                    layers.push(data);
                }
            })
        }
        generate(layerDatas)

        setLayers(layers.map(layerInfo => {
            let style;
            if (layerInfo.style) {
                let styleJson = {};
                if (layerInfo.style.fill) {
                    styleJson.fill = new Fill({
                        ...layerInfo.style.fill
                    });
                }
                if (layerInfo.style.stroke) {
                    styleJson.stroke = new Stroke({
                        ...layerInfo.style.stroke
                    });
                }

                if (layerInfo.style.circle) {
                    const circle = { ...layerInfo.style.circle }
                    if (circle.fill) {
                        circle.fill = new Fill({
                            ...circle.fill
                        })
                    }
                    if (circle.stroke) {
                        circle.stroke = new Stroke({
                            ...circle.stroke
                        })
                    }
                    styleJson.image = new Circle({
                        ...circle
                    });
                }
                style = new Style(styleJson)
            }

            const l = new VectorLayer({
                name: layerInfo.title,
                visible: false,
                style,
                source: new VectorSource({
                    loader: function (extent, resolution, projection, success, failure) {
                        if (layerInfo.dl === 'zhfx') {
                            ZhfxApi.list({
                                yhlx: layerInfo.title,
                            }).then(resp => {
                                cacheDatas[layerInfo.title] = resp.rows;
                                /* 部分数据只有经纬度，无坐标信息，在此处理一下 */
                                const abcd = resp.rows.map(e => {
                                    if (e?.geom) {
                                        return e
                                    } else if (!e?.geom && e.jd && e.wd) {
                                        return { ...e, geom: `POINT(${e.jd} ${e.wd})` }
                                    }
                                    return e;
                                })
                                //console.log('1', abcd)
                                /*  */
                                const features = abcd.filter(data => data.geom).map(data => {
                                    const feature = dataToFeature(data);
                                    const yhlx = layerInfo.title;
                                    // console.log('layerInfo.title',yhlx)
                                    // console.log('layerInfo',layerInfo)
                                    const iconStyle = new Style({
                                        image: new Icon({
                                            src: resourcePath.iconMap[yhlx],
                                            scale: resourcePath?.scales?.[yhlx + '_scale'] || 0.6,
                                            anchor: [0.5, 1]
                                        })
                                    })
                                    //console.log('layerInfo', feature, iconStyle)
                                    feature.setStyle(iconStyle)
                                    feature.set('layerName', layerInfo.title)
                                    return feature;
                                })
                                // map.getView().fit(features[0].getGeometry())
                                this.addFeatures(features)
                                // success(features);
                            })
                        }
                        else if (layerInfo.dl === 'czt') {
                            ZdfhApi.list({
                                cztxl: layerInfo.title
                            }).then(resp => {
                                cacheDatas[layerInfo.title] = resp.rows;
                                const features = resp.rows.filter(data => {
                                    if (data.geom) {
                                        return data.geom
                                    } else if (data.xq) {
                                        const a = JSON.parse(data.xq)
                                        if (a.longitude && a.latitude) {
                                            data.geom = `POINT(${a.longitude} ${a.latitude})`
                                            return data.geom
                                        }
                                    }

                                }).map(data => {
                                    const feature = dataToFeature(data);
                                    const cztxl = layerInfo.title;
                                    const iconStyle = new Style({
                                        image: new Icon({
                                            src: resourcePath.iconMap[cztxl],
                                            scale: resourcePath?.scales?.[cztxl + '_scale'] || 0.6,
                                            anchor: [0.5, 1]
                                        })
                                    })
                                    feature.setStyle(iconStyle)
                                    feature.set('layerName', layerInfo.title)
                                    return feature;
                                })
                                // map.getView().fit(features[0].getGeometry())
                                this.addFeatures(features)
                                // success(features);
                            })
                        } else if (layerInfo.dl === 'jzzy') {
                            JzzyApi.list({
                                jzzyxl: layerInfo.title
                            }).then(resp => {
                                cacheDatas[layerInfo.title] = resp.rows;
                                const features = resp.rows.filter(data => data.geom).map(data => {
                                    const feature = dataToFeature(data);
                                    const jzzyxl = layerInfo.title;
                                    const iconStyle = new Style({
                                        image: new Icon({
                                            src: resourcePath.iconMap[jzzyxl],
                                            scale: resourcePath?.scales?.[jzzyxl + '_scale'] || 0.6,
                                            anchor: [0.5, 1]
                                        })
                                    })
                                    feature.setStyle(iconStyle)
                                    feature.set('layerName', layerInfo.title)
                                    return feature;
                                })
                                // map.getView().fit(features[0].getGeometry())
                                this.addFeatures(features)
                                // success(features);
                            })
                        }
                        else if (layerInfo.dl === 'zdfh') {
                            if (layerInfo.title === "监测监控台站") {
                                ZdfhApi.monitor({
                                    jcdlx: layerInfo.title
                                }).then(resp => {
                                    cacheDatas[layerInfo.title] = resp.rows;
                                    const features = resp.rows.filter(data => data.geom
                                    ).map(data => {
                                        const feature = dataToFeature(data);
                                        const jcdlx = layerInfo.title;
                                        const iconStyle = new Style({
                                            image: new Icon({
                                                src: resourcePath.iconMap[jcdlx],
                                                scale: resourcePath?.scales?.[jcdlx + '_scale'] || 0.6,
                                                anchor: [0.5, 1]
                                            })
                                        })
                                        feature.setStyle(iconStyle)
                                        feature.set('layerName', layerInfo.title)
                                        return feature;
                                    })
                                    this.addFeatures(features)
                                })
                            }
                            else {
                                ZdfhApi.list({
                                    cztxl: layerInfo.title
                                }).then(resp => {
                                    cacheDatas[layerInfo.title] = resp.rows;
                                    const features = resp.rows.filter(data => {
                                        if (data?.fhjb > 2) {
                                            return data.geom
                                        } else {
                                            return null;
                                        }
                                    }
                                    ).map(data => {
                                        const feature = dataToFeature(data);
                                        const cztxl = layerInfo.title;
                                        const iconStyle = new Style({
                                            image: new Icon({
                                                src: resourcePath.iconMap[cztxl],
                                                scale: 0.6,
                                                anchor: [0.5, 1]
                                            })
                                        })
                                        feature.setStyle(iconStyle)
                                        feature.set('layerName', layerInfo.title)
                                        return feature;
                                    })
                                    this.addFeatures(features)
                                })
                            }

                        }
                    }
                })
            });
            l.set('__tpye', 'businessLayer')
            l.set('dl', layerInfo.dl)
            map.addLayer(l)
            return l;
        }))

    }, [map, layerDatas])

    useEffect(() => {
        const handler = evt => {
            const features = map.getFeaturesAtPixel(evt.pixel);
            const targetFeature = features?.find(f => {
                return f.get('cztmc') || f.get('jzzymc') || f.get('yhmc');
            })
            if (targetFeature) {
                map.dispatchEvent({
                    type: 'detail.show',
                    title: targetFeature.get('cztmc') || targetFeature.get('jzzymc') || targetFeature.get('yhmc'),
                    component: <DataDetail item={targetFeature.getProperties()} cztxl={targetFeature.get('cztxl')}
                        jzzyxl={targetFeature.get('jzzyxl')} yhlx={targetFeature.get('yhlx')} />
                })
            }
        }
        map.on('singleclick', handler);
        return () => {
            map.un('singleclick', handler);
        }
    }, [map])

    useEffect(() => {
        return () => {
            layers?.forEach(layer => {
                map.removeLayer(layer);
            })
        }
    }, [layers, map])

    return <>
        <PanelLeft style={{
            // top: 98
        }}>
            <BlockPanel title={"资源目录"}>
                {layerDatas.map(layerData => {
                    return <Collapse key={layerData.title} defaultActiveKey={['灾害风险', '承灾体', '减灾资源', '重点防护目标']} style={{
                        marginBottom: 12
                    }}>
                        <Collapse.Panel key={layerData.title} header={layerData.title}>
                            <Tree treeData={layerData.children} fieldNames={{
                                title: 'count',
                                key: 'title',
                                children: 'children',
                            }} checkable
                                onCheck={(checkedKeys, { checked, checkedNodes }) => {
                                    layers.filter(layer => {
                                        return layer.get('dl') === layerData.dl;
                                    }).forEach(layer => {
                                        if (checkedKeys.find(key => key === layer.get('name'))) {
                                            layer.set('visible', true)
                                        } else {
                                            layer.set('visible', false)
                                        }
                                    }
                                    );

                                }}
                            />
                        </Collapse.Panel>
                    </Collapse>
                })}
            </BlockPanel>
        </PanelLeft>
        <MapPointerMove field={fields} />
        {/* <Toolbar /> */}
    </>;
}